
#include "sciter-x.h"
#include "sciter-x-behavior.h"
#include "sciter-x-threads.h"
#include "sciter-x-video-api.h"

#include "lvgl_init.h"
#include "AppRouter.h"

namespace sciter
{
	struct watch_screen_stream : public event_handler
	{
		sciter::om::hasset<sciter::video_destination> rendering_site;

		watch_screen_stream() {}
		virtual ~watch_screen_stream() {}

		// 订阅事件类型
		virtual bool subscription(HELEMENT he, UINT& event_groups)
		{
			event_groups = HANDLE_BEHAVIOR_EVENT; // 订阅事件
			return true;
		}

		// 附着到界面元素
		virtual void attached(HELEMENT he) { 

  			AppRouter::GetInstance()->AppInit();
 			AppRouter::GetInstance()->GoNext("Pages/Startup");

			// lvgl事件循环
			std::thread([=]() {
				while (1) {
					lv_task_handler();
					std::this_thread::sleep_for(std::chrono::milliseconds(5));
				}
				}).detach();
		}

		// 与界面元素分离
		virtual void detached(HELEMENT he) { asset_release(); }

		// behavior事件处理
		virtual bool on_event(HELEMENT he, HELEMENT target, BEHAVIOR_EVENTS type, UINT_PTR reason)
		{
			if (type != VIDEO_BIND_RQ)
				return false;

			if (!reason)
				return true; // first phase, consume the event to mark as we will provide frames
			
			rendering_site = (sciter::video_destination*)reason;
			sciter::om::hasset<sciter::video_destination> fsite;

			if (rendering_site->asset_get_interface(FRAGMENTED_VIDEO_DESTINATION_INAME, fsite.target()))
			{
				sciter::thread(thread_render_frame, fsite);
			}

			return true;
		}

		// 获取准备好的buf, 并执行帧渲染
		static void thread_render_frame(sciter::om::hasset<sciter::video_destination> rendering_site) {
			
			// 视频流
			rendering_site->start_streaming(DISP_HOR_RES, DISP_VER_RES, COLOR_SPACE_RGB32);
			while (rendering_site->is_alive())
			{
				if (g_monitor.refr_qry) {
					// 渲染帧
					rendering_site->render_frame((const unsigned char*)g_monitor.tft_fb, sizeof(unsigned int) * DISP_HOR_RES * DISP_VER_RES);
					g_monitor.refr_qry = false;
				}
			} 
		}
	};

	struct watch_screen_stream_factory : public behavior_factory {

		watch_screen_stream_factory() : behavior_factory("watch-screen") { }

		virtual event_handler* create(HELEMENT he) { return new watch_screen_stream(); }

	};

	watch_screen_stream_factory watch_screen_stream_factory_instance;
}
